<?php

namespace Frieza\Modules\Position\Controllers;

use Biz\model\advertisement\MCustomCard;
use Biz\service\advertisement\apiModule\CardWithPos;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\service\position\apiModule\HomeRecommendCard;
use Doraemon\tools\BlockType;
use Doraemon\tools\BlockTypeMapping;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Exception;
use Illuminate\Http\Request;


class HomeRecommendCardController extends BaseController
{
    use BaseTrait;

    public $base_field_ext_type = CardWithPos::CARD_EXT_TYPE_BANNER;

    /**
     * @throws Exception
     */
    public function saveModule(Request $request, $baseInfoId)
    {
        $pos = $request->input('base.pos', 0);
        if ($pos <= 0)  throw new Exception('展示位置必选大于0');

        if ($this->base_field_pos && ($this->base_field_pos != $pos)) throw new Exception('展示位置不允许变更');

        $ext_type = $request->input("base.ext_type", "");
        if ($ext_type == CardWithPos::CARD_EXT_TYPE_BANNER) {
            $base = $request->input('base', []);
            $rules = $request->input('rules', []);
            $pic_id = $request->input("double_pic_id", "");
            if (empty($pic_id)) throw new Exception('图片必须上传');
            $id = $base['id'] ?? 0;
            $copy_id = $base['copy_id'] ?? 0;
            $img_size = $rules['img_size'] ?? 0;
            if (($id > 0 || $copy_id > 0) && $img_size == 0) {

            } else {
                $this->rulesValid($rules);
            }
        } else if ($ext_type == CardWithPos::CARD_EXT_TYPE_TOPIC) {
            $topic = $request->input('card_topic', []);
            if (empty($topic['photo'])) throw new Exception('背景图必须上传');
            if (empty($topic['module_icon'])) throw new Exception('模块图标必须上传');
            if (empty($topic['sub_title'])) throw new Exception('标题必须填写');
            if (empty($topic['ranking_link']['link_type'])) throw new Exception('链接必须选择');
            $entity = new MCustomCard();
            $entity->photo = $topic['photo'];
            $entity->module_icon = $topic['module_icon'];
            $entity->sub_title = $topic['sub_title'];
            $entity->convert = $topic['convert'];
            $entity->link_type = $topic['ranking_link']['link_type'];
            $entity->link_params = $topic['ranking_link']['link_params'];
            $entity->linked_id = $baseInfoId;
            $entity::saved($entity);
        } else if ($ext_type == CardWithPos::CARD_EXT_TYPE_SIMILAR) {
            $similar = $request->input('card_similar', []);
            if (empty($similar['photo'])) throw new Exception('封面图必须上传');
            if (empty($similar['main_title'])) throw new Exception('主标题必须填写');
            if (empty($similar['sub_title'])) throw new Exception('副标题必须填写');
            if (empty($similar['ranking_link']['link_type'])) throw new Exception('链接必须选择');
            $entity = new MCustomCard();
            $entity->photo = $similar['photo'];
            $entity->module_icon = $similar['module_icon'];
            $entity->main_title = $similar['main_title'];
            $entity->sub_title = $similar['sub_title'];
            $entity->bottom_background_image = $similar['bottom_background_image'];
            $entity->convert = $similar['convert'];
            $entity->link_type = $similar['ranking_link']['link_type'];
            $entity->link_params = $similar['ranking_link']['link_params'];
            $entity->linked_id = $baseInfoId;
            $entity::saved($entity);
        }
    }

    public function extendList(Grid $grid)
    {
        $grid->column('pos', '展示位置')->label($this->labelColor());
        $grid->column('card_info', '卡片信息')->display(function ($title, Grid\Column $column) {
            $display = [CardWithPos::CARD_EXT_MAP_HOME[$this->ext_type] ?? CardWithPos::CARD_EXT_MAP_HOME[CardWithPos::CARD_EXT_TYPE_BANNER]];
            if ($this->ext_type == CardWithPos::CARD_EXT_TYPE_CONTENT) {
                $display[] = "内容类型:" . BlockType::name($this->obj_type);
                $display[] = "内容id:" . $this->obj_id;
            } else {
                $images[] = "<img src='{$this->double_pic_url}' style=\"max-width:200px;max-height:200px\" class=\"img img-thumbnail\"/>";
                if ($this->double_pic_url) $display[] = implode('<br/><br/>', $images);
            }

            return implode('<br/>', $display);
        });
    }

    public function extendSaveBaseInfo(Request $request): array
    {
        $ext_type = $request->input("base.ext_type", "");
        $link = [];
        switch ($ext_type) {
            case CardWithPos::CARD_EXT_TYPE_BANNER:
                $single_pic_id = $request->input("single_pic_id", "");
                $double_pic_id = $request->input("double_pic_id", "");
                $pic_id = json_encode(compact('single_pic_id', 'double_pic_id'));
                //链接处理
                $imgLink = $request->input("base.link", []);
                $link_type = $imgLink['link_type'] ?? '';
                $link_params = isset($imgLink['link_params']) ? json_encode($imgLink['link_params'], JSON_UNESCAPED_UNICODE) : '';
                $link = compact('link_type', 'link_params');
                break;
            case CardWithPos::CARD_EXT_TYPE_CONTENT:
                $obj = $request->input("obj", []);
                $link_type = $obj['link_type'] ?? '';
                $link_params = isset($obj['link_params']) ? json_encode($obj['link_params'], JSON_UNESCAPED_UNICODE) : '';
                $link = compact('link_type', 'link_params');
                $objRs = BlockTypeMapping::getObjFromLinkParams($link_type, $link_params);
                $obj_id = $objRs['obj_id'] ?? null;
                $obj_type = $objRs['obj_type'] ?? null;
                $pic_id = json_encode(compact('obj_id', 'obj_type'));
                break;
            default:
                $pic_id = '';
                break;
        }

        return ['pic_id' => $pic_id, 'ext_type' => $ext_type] + $link;
    }

    public function beforeTitleForm(Form $form)
    {
        $help = [
            "受轮播和今日整屋影响，前台展示位置=当前数值+2",
        ];
        if ($this->relation) {
            $form->text('base.pos', '展示位置')->readonly()->help("<span style='color: red'>" . implode('<br/>', $help) . "</span>");
        } else {
            $form->number('base.pos', '展示位置')->placeholder('位置')->required()->help("<span style='color: red'>" . implode('<br/>', $help) . "</span>");
        }
    }

    public function beforeLinkForm(Form $form)
    {
        $form->radio('base.ext_type', '卡片类型')
            ->options(CardWithPos::CARD_EXT_MAP_HOME)
            ->when(CardWithPos::CARD_EXT_TYPE_BANNER, function (Form $form) {
                $this->bannerFormWithCheck($form, 'double_pic_id', '双列Banner');
                $form->multiLinkSelect('base.link', 'Banner跳转链接');
            })->when(CardWithPos::CARD_EXT_TYPE_CONTENT, function (Form $form) {
                $allowLink = [
                    LinkConf::LINK_PHOTO,
                    LinkConf::LINK_ARTICLE,
                    LinkConf::LINK_GUIDE,
                    LinkConf::LINK_BLANK,
                    LinkConf::LINK_TOPIC_DETAIL,
                    LinkConf::LINK_INSPIRATION_SET,
                    LinkConf::LINK_APP_WIKI_LIST_DETAIL,
                ];
                $form->multiLinkSelect('obj', '内容', $allowLink)->help('支持图片note、视频note、整屋案例、指南文章、回答、经验文章、话题、收藏夹、好物清单');
            })->when(CardWithPos::CARD_EXT_TYPE_TOPIC, function (Form $form) {

                $form->imgUpload('card_topic.photo', '背景图');
                $form->imgUpload('card_topic.module_icon', '模块图标');
                $form->text('card_topic.sub_title', '标题');
                $form->radio('card_topic.convert', '引导模块')->options([0 => '隐藏', 1 => '展示']);
                $form->multiLinkSelect('card_topic.ranking_link', '跳转链接');

            })->when(CardWithPos::CARD_EXT_TYPE_SIMILAR, function (Form $form) {

                $form->imgUpload('card_similar.photo', '封面图');
                $form->imgUpload('card_similar.module_icon', '模块图标');
                $form->text('card_similar.main_title', '主标题');
                $form->text('card_similar.sub_title', '副标题');
                $form->imgUpload('card_similar.bottom_background_image', '文字区背景图');
                $form->text('card_similar.convert', '发布者uid');
                $form->multiLinkSelect('card_similar.ranking_link', '跳转链接');
            });
    }
}

